<%@ page language="java" contentType="text/html; charset=UTF-8"	 pageEncoding="UTF-8"%>
<%@ include file="../include/laypublic.jsp" %>
<!DOCTYPE html>
<html>
<head>
  <title>内部协议补充协议</title>
</head>
<script type="text/html" id="layui-row"  >
    <div class="layui-row" id="{0}" >
        <div class="contract-box" >
            <div class="contract-money">
                <table class="layui-table">
                    <colgroup>
                        <col width="90">
                        <col width="200">
                        <col width="200">
                        <col width="200">
                        <col width="200">
                        <col width="200">
                        <col width="200">
                        <col width="150">
                    </colgroup>
                    <thead>
                    <tr>
                        <td>子项名称<input type="hidden" value="{1}"  name="subNames"  class="subNames" /></td>
                        <td class=tg-c >{1}</td>                        
                        <td></td>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td></td>
						<td class=tg-c ><button type="button" class="layui-btn layui-btn-sm del-layui-row" title="删除子项"  ><i class="layui-icon">&#xe640;</i></button></td>
                    </tr>
                    </thead>
                    <tbody>
                    <tr>
                        <th>序号</th>
                        <th >费用类型</th>
                        <th>项目合同_对外建安费(元)(下浮前)</th>
                        <th>总包合同_对外建安费(元)(下浮前)</th>
                        <th>对外下浮率(%)</th>
 						<th>对内下浮率(%)</th>
                        <th>对内合同价(元)(下浮后)</th>
						<th></th>
                    </tr>
                    </tbody>
                    <tbody >
                    <tr id="{0}Row-1" level=1 >
                        <td><span class="label" >1</span><input type="hidden" value="1" name="orderIdxs" /><input type="hidden" value="{0}" name="agrtSubIds" /></td>
                        <td  class=tg-c  ><b>建安工程费</b><input type="hidden" value="1" name="feeTypes" /><input type="hidden" value="{1}"  name="itemNameSub"  class="itemNameSub" /><input type="hidden" value="-1" name="feeSmallTypes" /><input type="hidden" value="建安工程费" name="typeNames" class="typeNames" /></td>
                        <td><input type="text" name="proContractPreFees" readonly style="border:0px"  autocomplete="off" class="layui-input projectamountbefore" /></td>
  						<td><input type="text" name="packPreFees" readonly style="border:0px" autocomplete="off" class="layui-input totalpackageamountbefore" /></td>
                        <td><input type="text" name="outDownRates" readonly style="border:0px"  autocomplete="off" class="layui-input outdiscount" /></td>
 						<td><input type="text" name="innerDownRates" readonly style="border:0px" autocomplete="off" class="layui-input indiscount" /></td>
                        <td><input type="text" name="afterDownFees" readonly style="border:0px"  autocomplete="off" class="layui-input inamountafter" /></td>
                        <td class=tg-c ><button type="button" class="layui-btn layui-btn-sm add-new-row" ><i class="layui-icon">&#xe654;</i></button></td>
                    </tr>
                    <tr id="sub{0}Row-1.1"  level=2 >
                        <td><span class="label">1.1</span> <input type="hidden" value="1.1" name="orderIdxs" /><input type="hidden" value="{0}" name="agrtSubIds" /></td>
                        <td  class=tg-c  ><label>土建</label><input type="hidden" value="1" name="feeTypes" /><input type="hidden" value="{1}" name="itemNameSub"  class="itemNameSub" /><input type="hidden" value="1.1" name="feeSmallTypes" /><input type="hidden" value="土建" name="typeNames"  class="typeNames"  /></td>
                   		<td><input type="text" name="proContractPreFees" readonly style="border:0px" lay-verify="required|floatNumber" autocomplete="off" class="layui-input decimal projectamountbefore" /></td>
  						<td><input type="text" name="packPreFees"  lay-verify="required|floatNumber" maxlength="13" autocomplete="off" class="layui-input  decimal totalpackageamountbefore" /></td>
                        <td><input type="text" name="outDownRates" readonly style="border:0px" lay-verify="required|floatNumber" autocomplete="off" class="layui-input decimal outdiscount" /></td>
 						<td><input type="text" name="innerDownRates" lay-verify="required|floatNumber" maxlength="6" autocomplete="off" class="layui-input decimal indiscount" /></td>
                        <td><input type="text" name="afterDownFees" readonly style="border:0px" lay-verify="required|floatNumber" autocomplete="off" class="layui-input inamountafter" /></td>                        
                        <td class=tg-c ><button type="button" class="layui-btn layui-btn-sm add-sub-row" ><i class="layui-icon">&#xe654;</i></button></td>
                    </tr>
                    <tr id="sub{0}Row-1.2"  level=2>
                        <td><span class="label">1.2</span> <input type="hidden" value="1.2" name="orderIdxs" /><input type="hidden" value="{0}" name="contractSubId" /></td>
                        <td  class=tg-c  ><label>安装</label><input type="hidden" value="1" name="feeTypes" /><input type="hidden" value="{1}" name="itemNameSub" class="itemNameSub" /><input type="hidden" value="1.2" name="feeSmallTypes" /><input type="hidden" value="安装" name="typeNames"  class="typeNames" /></td>
                   		<td><input type="text" name="proContractPreFees" readonly style="border:0px" lay-verify="required|floatNumber" autocomplete="off" class="layui-input decimal projectamountbefore" /></td>
  						<td><input type="text" name="packPreFees"  lay-verify="required|floatNumber" maxlength="13" autocomplete="off" class="layui-input  decimal totalpackageamountbefore" /></td>
                        <td><input type="text" name="outDownRates" readonly style="border:0px" lay-verify="required|floatNumber" autocomplete="off" class="layui-input decimal outdiscount" /></td>
 						<td><input type="text" name="innerDownRates" lay-verify="required|floatNumber" maxlength="6" autocomplete="off" class="layui-input decimal indiscount" /></td>
                        <td><input type="text" name="afterDownFees" readonly style="border:0px" lay-verify="required|floatNumber" autocomplete="off" class="layui-input inamountafter" /></td>                        
                        <td class=tg-c ><button type="button" class="layui-btn layui-btn-sm add-sub-row" ><i class="layui-icon">&#xe654;</i></button></td>
                    </tr>                   
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</script>



<script type="text/html" id="layui-row-tr" >
<tr id="{0}" level={1} >
<td><span class="label" >{2}</span><input type="hidden" value="{2}" name="orderIdxs" /><input type="hidden" value="{3}" name="agrtSubIds" /></td>
<td><input type="text" lay-verify="required" maxlength="50" value="{4}" autocomplete="off" class="layui-input typeNames" name="typeNames" />
<input type="hidden" value="{5}" name="feeTypes" class="feeTypes" />
<input type="hidden" value="{6}" name="feeSmallTypes" class="feeSmallTypes" />
<input type="hidden" value="{7}" name="itemNameSub" class="itemNameSub" />
</td>
<td><input type="text" value="{8}" name="proContractPreFees" lay-verify="required|floatNumber" maxlength="13" autocomplete="off" class="layui-input decimal projectamountbefore" /></td>
<td><input type="text" value="{9}" name="packPreFees"  lay-verify="required|floatNumber" maxlength="13" autocomplete="off" class="layui-input decimal totalpackageamountbefore" /></td>
<td><input type="text" value="{10}" name="outDownRates" lay-verify="required|floatNumber" maxlength="6" autocomplete="off" class="layui-input decimal outdiscount" /></td>
<td><input type="text" value="{11}" name="innerDownRates" lay-verify="required|floatNumber" maxlength="6" autocomplete="off" class="layui-input decimal indiscount" /></td>
<td><input type="text" value="{12}" readonly style="border:0px" name="afterDownFees" lay-verify="required|floatNumber" autocomplete="off" class="layui-input inamountafter" /></td>
<td class=tg-c ><button type="button" class="layui-btn layui-btn-sm add-sub-row" ><i class="layui-icon">&#xe654;</i></button></td>
</tr>
</script>

<script type="text/html" id="layui-row-tr2" >
<tr id="{0}" level={1} >
<td><span class="label" >{2}</span><input type="hidden" value="{2}" name="orderIdxs" /><input type="hidden" value="{3}" name="extSubIds" /></td>
<td><input type="text" lay-verify="required" maxlength="50" value="{4}" autocomplete="off" class="layui-input typeNames" name="typeNames" />
<input type="hidden" value="{5}" name="feeTypes" class="feeTypes" />
<input type="hidden" value="{6}" name="feeSmallTypes" class="feeSmallTypes" />
<input type="hidden" value="{7}" name="itemNameSub" class="itemNameSub" />
</td>
<td><input type="text" value="{8}" name="proContractPreFees" lay-verify="required|floatNumber" maxlength="13" autocomplete="off" class="layui-input decimal projectamountbefore" /></td>
<td><input type="text" value="{9}" name="packPreFees"  lay-verify="required|floatNumber" maxlength="13" autocomplete="off" class="layui-input decimal totalpackageamountbefore" /></td>
<td><input type="text" value="{10}" name="outDownRates" lay-verify="required|floatNumber" maxlength="6" autocomplete="off" class="layui-input decimal outdiscount" /></td>
<td><input type="text" value="{11}" name="innerDownRates" lay-verify="required|floatNumber" maxlength="6" autocomplete="off" class="layui-input decimal indiscount" /></td>
<td><input type="text" value="{12}" readonly style="border:0px" name="afterDownFees" lay-verify="required|floatNumber" autocomplete="off" class="layui-input inamountafter" /></td>
<td class=tg-c ><button type="button" class="layui-btn layui-btn-sm del-sub-row" ><i class="layui-icon">&#xe640;</i></button></td>
</tr>
</script>

<style>
.list-title{
	display:block;
	width:270px;
	text-align:right;
	left:5px;
	font-size:.89em;
}

.pos-r{
	position: relative;
}
.pos-a{
	position: absolute;
}

.margin-bot10 {
	margin-bottom: 10px;
}

.margin-lt10 {
	margin-left: 10px;
}

.layui-row+.layui-row {
	margin-top: 10px;
}

.tg-l {
	text-align: left;
}

.tg-c {
	text-align: center;
}

.tg-r {
	text-align: right;
}

.contract-list {
	margin-top: 20px;
}

.contract-box {
	width: 100%;
	min-height: 100px;
}

.contract-money {
	width: 94%;
	margin: 0px auto;
}

.contract-money .layui-table {
	margin: 0;
}

.contract-money th {
	text-align: center;
	height: 38px;
}

.contract-money .label {
	display: block;
	width: 45px !important;
	margin-left: 15px;
}

.fieldset {
	margin-top: 5px;
	margin-bottom: 0px
}

.layui-legend {
	background-color: #5fb878;
	font-size: 15px !important;
	width: 140px;
}

.layui-form-item {
	margin-bottom: 5px;
	clear: both;
	*zoom: 1;
}

.layui-form-label {
	width: 160px;
}
</style>
<body>
	<div class="layui-fluid">
		<div class="layui-card">
			<div style="padding-top: 15px;">&nbsp;</div>
			<form class="layui-form" id="addInfo_form" lay-filter="addInfo_form">
				<div class="layui-tab layui-tab-brief" >
					<div class="layui-tab-content">
						<div class="layui-tab-item layui-show">
							<fieldset class="layui-elem-field layui-field-title fieldset" id="baseInfo" >
								<legend class="layui-btn layui-legend"
									style="text-align: left; cursor: default;" >项目基础信息 ></legend>
								<input type="hidden" name="judge" value="2">
								<div class="layui-form-item">
									<div class="layui-inline">
										<label class="layui-form-label">申请公司</label>
										<div class="layui-input-inline">
											<input type="hidden" name="hrOrgid" value="${bindOrgId}">
											<input type="text" value="${bindOrgName}"
												style="border: 0px;width:220px" readonly="readonly" class="layui-input">
										</div>
									</div>
									<div class="layui-inline">
										<label class="layui-form-label">申请部门</label>
										<div class="layui-input-inline">
											<input type="hidden" name="hrDeptid" value="${bindDeptId}">
											<input type="text" value="${bindDeptName}"
												style="border: 0px;" readonly="readonly" class="layui-input">
										</div>
									</div>
									<div class="layui-inline">
										<label class="layui-form-label">申请人</label>
										<div class="layui-input-inline">
											<input type="hidden" name="hrStaffApplyid"
												value="${SESSION_KEY_USER_DETAIL.hrStaffId }"> <input
												type="text" name="staffname" value="${staffName }"
												readonly="readonly" style="border: 0px" autocomplete="off"
												class="layui-input">
										</div>
									</div>
								</div>
								<div class="layui-form-item">
									<div class="layui-inline">
										<label class="layui-form-label">项目名称</label>
										<div class="layui-input-inline">
											<select id="add_select_proId" name="proCodeAndCodes"
												lay-filter="add_select_proId" lay-verify="required"
												lay-search>
												<option value="">请选择-项目名称</option>
												<c:if test="${not empty InnerAgrtList }">
													<c:forEach items="${InnerAgrtList}" var="InnerAgrt">
														<option value="${InnerAgrt.proCode }_${InnerAgrt.id }_${InnerAgrt.proName }">${InnerAgrt.proName }_${InnerAgrt.innerAgrtName }
														</option>
													</c:forEach>
												</c:if>
											</select>
										</div>
									</div>
									<div class="layui-inline">
										<label class="layui-form-label">项目编号</label>
										<div class="layui-input-inline">
											<input type="text" id="id_proCode" name="proCode" value="" style="border: 0px;"
												readonly="readonly" class="layui-input">
										</div>
									</div>
									<div class="layui-inline">
										<label class="layui-form-label">区域公司</label>
										<div class="layui-input-inline">
											<input type="hidden" id="areaId" name="hrOrgAreaId" value="">
											<input type="text" id="id_regionalCompany"
												value="" readonly="readonly"
												style="border: 0px;width:220px" autocomplete="off" class="layui-input">
										</div>
									</div>
								</div>
								<div class="layui-form-item">
									<div class="layui-inline">
										<label class="layui-form-label">项目公司</label>
										<div class="layui-input-inline">
											<input type="hidden" id="compId" name="hrOrgProId" value=""> <input
												type="text" id="id_projectCompany" value=""
												style="border: 0px;width:220px" readonly="readonly" class="layui-input">
										</div>
									</div>
									<div class="layui-inline">
										<label class="layui-form-label">实施机构</label>
										<div class="layui-input-inline">
											<input type="text" id="id_ImplementingBody" name="carryOrg" style="border: 0px;width:220px"
												readonly="readonly" class="layui-input">
										</div>
									</div>

									<div class="layui-inline">
										<label class="layui-form-label">项目地址</label>
										<div class="layui-input-inline">
											<input type="hidden" id="sgCityId" name="sgCityId" value="">
											<input type="text" id="id_projectAddress" name="projectAddress" value=""
												style="border: 0px;" readonly="readonly" class="layui-input">
										</div>
									</div>
								</div>
								<div class="layui-form-item">
									<div class="layui-inline">
										<label class="layui-form-label">项目负责人</label>
										<div class="layui-input-inline">
											<input type="text" id="id_projectLeader" name="proLeader" style="border: 0px;"
												readonly="readonly" maxlength="10" lay-verify="required|COC"
												class="layui-input">
										</div>
									</div>
									<div class="layui-inline">
										<label class="layui-form-label">内部协议名称</label>
										<div class="layui-input-inline">
											<input type="text" id="id_internalAgreementName" name="innerAgrtName"
												style="border: 0px;width:220px" readonly="readonly" lay-verify="required|COC"
												class="layui-input">
										</div>
									</div>
									<div class="layui-inline">
										<label class="layui-form-label">合同单位名称</label>
										<div class="layui-input-inline">
											<input type="hidden" id="sgCoopId" name="sgCoopIds" value="">
											<input type="text" id="id_contractUnitName"
												style="border: 0px;width:220px" readonly="readonly" lay-verify="required|COC"
												class="layui-input">												
										</div>
									</div>
								</div>
								<div class="layui-form-item">
									<div class="layui-inline">
										<label class="layui-form-label" >补充协议名称</label>
										<div class="layui-input-inline">
											<input type="text" class="layui-input" maxlength="100" id="id_supplementaryAgreementName" name="innerAgrtSaName" lay-verify="required|COC" autocomplete="off" placeholder="请输入补充协议名称" />
										</div>
									</div>
									<div class="layui-inline">
										<label class="layui-form-label" >补充协议编码</label>
										<div class="layui-input-inline" >
										    <input type="text" class="layui-input" maxlength="50" id="id_supplementaryAgreementCode" name="innerAgrtSaCode" autocomplete="off" placeholder="请输入补充协议编码" />											
										</div>
									</div>
									<div class="layui-inline">
										<label class="layui-form-label">补充协议签订日期</label>
										<div class="layui-input-inline">
											<input type="text" class="layui-input" id="id_supplementaryAgreementSigningDate" name="signDate" autocomplete="off" placeholder="补充协议签订日期" />
										</div>
									</div>
								</div>
								<div class="layui-form-item">
									<label class="layui-form-label">补充内容说明</label>
									<div class="layui-input-block">
										<textarea id="id_supplementaryContentDesc" name="saMemo"
											placeholder="请输入最多500字"
											class="layui-textarea" maxlength="500" lay-verify="required"
											style="width: 899px; height: 180px;"></textarea>
									</div>
								</div>								
							</fieldset>						
							<fieldset class="layui-elem-field layui-field-title fieldset" id="contractPriceInfo" >
								<legend class="layui-btn layui-legend" style="text-align: left; cursor: default;" >合同价款信息 ></legend>
								<div class="layui-form-item">
									<div class="layui-inline">
										<label class="layui-form-label" >合同总价(元)(下浮前)</label>
										<div class="layui-input-inline">
											<input type="text"  lay-verify="required|floatNumber" id="preTotalSumId" name="preTotalSum" onblur="arabiaToCN(this,1);" readonly="readonly" style="border:0px" class="layui-input" >
										</div>
									</div>
									<div class="layui-inline">
										<label class="layui-form-label">合同总价(元)(下浮后)</label>
										<div class="layui-input-inline">
											<input type="text"  lay-verify="required|floatNumber" id="afterTotalSumId" name="afterTotalSum" onblur="arabiaToCN(this,1);" readonly="readonly" style="border:0px" class="layui-input" >
										</div>
									</div>
									<div class="layui-inline">
										<label class="layui-form-label">整体下浮率(%)</label>
										<div class="layui-input-inline">
											<input type="text" lay-verify="required|floatNumber" id="totalRateId" name="totalRate" readonly="readonly" style="border:0px" class="layui-input" >
										</div>
									</div>
								</div>								
								<div class="layui-form-item">
									<label class="layui-form-label pos-r"><b class="pos-a list-title">合同价款清单>></b></label> 
								</div>
								<div class="contract-list" >
																	
									<div class="contract-box margin-bot10" >
	            						<div class="contract-money">
	                						<table class="layui-table">
							                    <colgroup>
							                        <col width="100"  >
							                        <col width="290"  >
							                        <col width="290" >
							                        <col width="290" >
							                        <col width="290" >
							                        <col width="290" >
							                    </colgroup>
												<thead>
													<tr>
														<th></th>
														<th>项目合同_对外建安费(元)(下浮前)</th>
														<th>总包合同_对外建安费(元)(下浮前)</th>
														<th>对外下浮率(%)</th>
														<th>对内下浮率(%)</th>
														<th>对内合同价(元)(下浮后)</th>
													</tr>
												</thead>
												<tbody >
													<tr>
													    <td class="tg-r" >合计</td>
														<td><input type="text" id="projectamountbefore" name="proContractPreSum" readonly style="border:0px" onblur="arabiaToCN(this,1);" lay-verify="required|floatNumber" class="layui-input " /></td>
														<td><input type="text" id="totalpackageamountbefore" name="preTotalSumTotal" readonly style="border:0px" onblur="arabiaToCN(this,1);" lay-verify="required|floatNumber" class="layui-input " /></td>
														<td><input type="text" id="outdiscount" name="outDownRate" readonly style="border:0px" lay-verify="required|floatNumber" class="layui-input " /></td>
														<td><input type="text" id="indiscount" name="innerDownRate" readonly style="border:0px" lay-verify="required|floatNumber" class="layui-input " /></td>
														<td><input type="text" id="inamountafter" name="afterTotalSumTotal" readonly style="border:0px" onblur="arabiaToCN(this,1);" lay-verify="required|floatNumber" class="layui-input " /></td>
													</tr>
								                </tbody>
							                </table>
	                    				</div>
                    				</div> 
								</div>							
							</fieldset>
																								
							<fieldset class="layui-elem-field layui-field-title fieldset" id="contractInfo" >
								<legend class="layui-btn layui-legend" style="text-align: left; cursor:default;" >合同信息 ></legend>								
								<div class="layui-form-item" >
									<div class="layui-inline">
										<label class="layui-form-label">合同工期(年)</label>
										<div class="layui-input-inline">
											<input type="text" id="id_Contractconstructionperiodyear" name="periodYears"
												onblur="checkValueverifyNumber2(this);"
												lay-verify="required|floatNumber" maxlength="100"
												autocomplete="off" class="layui-input">
										</div>
									</div>
									<div class="layui-inline">
										<label class="layui-form-label">合同工期(天)</label>
										<div class="layui-input-inline">
											<input type="text" id="id_Contractoperationperiodyear" name="periodDays"
												maxlength="100" lay-verify="required|floatNumber" readonly style="border:0px"
												class="layui-input">
										</div>
									</div>
								</div>
								<div class="layui-form-item" >
									<div class="layui-inline">
										<label class="layui-form-label">合同开工日期</label>
										<div class="layui-input-inline">
											<input type="text" class="layui-input" autocomplete="off"
												id="id_contractCommencementDate" lay-verify="required"
												name="beginBuildDate">
										</div>
									</div>
									<div class="layui-inline">
										<label class="layui-form-label">合同竣工日期</label>
										<div class="layui-input-inline">
											<input type="text" id="id_contractCompletionDate" name="endBuildDate" readonly style="border:0px"
												lay-verify="required" autocomplete="off" class="layui-input">
										</div>
									</div>
								</div>
								<div class="layui-form-item">
									<div class="layui-inline">
										<label class="layui-form-label">实际开工日期 </label>
										<div class="layui-input-inline">
											<input type="text" id="id_actualCommencementDate" name="actBeginDate"
												lay-verify="required" autocomplete="off"
												class="layui-input">
										</div>
									</div>
									<div class="layui-inline">
										<label class="layui-form-label" >调整后竣工日期</label>
										<div class="layui-input-inline">
											<input type="text" id="id_adjustedCompletionDate" name="adjustEndDate" readonly style="border:0px"
												lay-verify="required" autocomplete="off" class="layui-input">
										</div>
									</div>
								</div>
								<div class="layui-form-item">
									<div class="layui-inline">
										<label class="layui-form-label" >实际竣工日期</label>
										<div class="layui-input-inline">
											<input type="text" id="id_practicalCompletionDate" name="actEndDate"
												autocomplete="off" class="layui-input">
										</div>
									</div>
								</div>
								<div class="layui-form-item">
									<div class="layui-inline">
										<label class="layui-form-label" >质量标准</label>
										<div class="layui-input-inline">
											<textarea id="id_priceAdjustmentMethod" name="qaStandard"
											class="layui-textarea" maxlength="100" lay-verify="required"
											style="width: 899px; height: 90px;"></textarea>
										</div>
									</div>
								</div>
								<div class="layui-form-item">
									<div class="layui-inline">
										<label class="layui-form-label" >预付款比例(%) </label>
										<div class="layui-input-inline" >
											<input type="text"  id="prePayRateId" name="prePayRate" value="0" lay-verify="required|floatNumber" 
												onblur="isNumberAndFloat1(this);" autocomplete="off" class="layui-input" />
										</div>
									</div>
									<div class="layui-inline">
										<label class="layui-form-label" >月度付款比例(%) </label>
										<div class="layui-input-inline" >
											<input type="text"  id="monthPayRateId" name="monthPayRate" value="70" lay-verify="required|floatNumber" 
												onblur="isNumberAndFloat1(this);" autocomplete="off" class="layui-input" />
										</div>
									</div>

									<div class="layui-inline">
										<label class="layui-form-label" >年度付款比例(%) </label>
										<div class="layui-input-inline" >
											<input type="text"  id="yearPayRateId" name="yearPayRate" value="75" lay-verify="required|floatNumber" 
												onblur="isNumberAndFloat1(this);" autocomplete="off" class="layui-input" />
										</div>
									</div>
								</div>
								<div class="layui-form-item">
									<div class="layui-inline">
										<label class="layui-form-label" >竣工验收后付款比例(%) </label>
										<div class="layui-input-inline" >
											<input type="text" id="checkAfterRateId"  name="checkAfterRate" value="85" lay-verify="required|floatNumber" 
												onblur="isNumberAndFloat1(this);" autocomplete="off" class="layui-input" />
										</div>
									</div>
									<div class="layui-inline">
										<label class="layui-form-label" >结算后付款比例(%) </label>
										<div class="layui-input-inline" >
											<input type="text" id="settleAfterRateId"  name="settleAfterRate" value="97" lay-verify="required|floatNumber" 
												onblur="isNumberAndFloat1(this);" autocomplete="off" class="layui-input" />
										</div>
									</div>
									<div class="layui-inline">
										<label class="layui-form-label" >质保金比例(%) </label>
										<div class="layui-input-inline" >
											<input type="text" id="qaEnsureRateId"  name="qaEnsureRate" value="3" lay-verify="required|floatNumber" 
												onblur="isNumberAndFloat1(this);" autocomplete="off" class="layui-input" />
										</div>
									</div>
								</div>
								<div class="layui-form-item">
									<div class="layui-inline">
										<label class="layui-form-label" >居间费承担方 </label>
										<div class="layui-input-inline">
											<select id="midFeeOrgNameId" name="midFeeOrgName" lay-verify="required">
											</select>
										</div>
									</div>
									<div class="layui-inline">
										<label class="layui-form-label" >农民工保证金承担方 </label>
										<div class="layui-input-inline">
											<select id="workersOrgNameId" name="workersOrgName" lay-verify="required">
											</select>
										</div>
									</div>
									<div class="layui-inline">
										<label class="layui-form-label" >履约保函承担方 </label>
										<div class="layui-input-inline">
											<select id="bondOrgNameId" name="bondOrgName" lay-verify="required">
											</select>
										</div>
									</div>
								</div>								
							</fieldset>								
							
							<fieldset class="layui-elem-field layui-field-title fieldset" id="comprehensivePlanInfo" >
								<legend class="layui-btn layui-legend" style="text-align: left; cursor: default;" >综合计划 ></legend>
								<div class="layui-form-item">
									<label class="layui-form-label"  >是否纳入综合计划考核</label>
									<div class="layui-input-inline">
										<select id="assessPlanFlagId" name="assessPlanFlag" lay-verify="required">
										</select>
									</div>
								</div>
								<div class="layui-form-item">
									<label class="layui-form-label pos-r"   ><b class="pos-a list-title"  >综合计划完成率对应月度付款比例>></b></label> 
								</div>	
								<div class="layui-form-item">
									<label class="layui-form-label"   ></label> 
								</div>						
								<div class="contract-box " id="plan-rate" >
            						<div class="contract-money"		>
                						<table class="layui-table"	>
							                    <colgroup>
							                        <col width="90"  >
							                        <col width="300" >
							                        <col width="300" >
							                        <col width="300" >
							                        <col width="250" >
							                    </colgroup>
												<thead>
													<tr>
														<th>序号</th>
														<th>综合计划完成率区间下限(>=)(%)</th>
														<th>综合计划完成率区间上限(<)(%)</th>
														<th>综合计划调整付款比例(%)</th>
														<th ></th>
													</tr>
												</thead>
												<tbody>
								                </tbody>
						                </table>
                    				</div>
                    			</div>                    
							</fieldset>

							
							<fieldset class="layui-elem-field layui-field-title fieldset"
								id="baseInfo">
								<legend class="layui-btn layui-legend"
									style="text-align: left; cursor: default;">附件></legend>
								<div style="margin-top: 20px;">
									<div class="layui-form-item">
										<label class="layui-form-label" style="width: 350px;">支持pdf、excel、word、图片资料，可上传多个</label>
									</div>
									<div class="layui-form-item">
										<label class="layui-form-label">Word版合同文本（选填）</label>
										<div class="layui-input-block">
											<div class="layui-upload">
												<button type="button" class="layui-btn" id="1-upload-more">上传</button>
												<div class="layui-upload-list" id="1-upload-more-list">
												</div>
											</div>
										</div>
									</div>
									<div class="layui-form-item">
										<label class="layui-form-label">PDF版合同文本（选填）</label>
										<div class="layui-input-block">
											<div class="layui-upload">
												<button type="button" class="layui-btn" id="2-upload-more">上传</button>
												<div class="layui-upload-list" id="2-upload-more-list">
												</div>
											</div>
										</div>
									</div>
									<div class="layui-form-item">
										<label class="layui-form-label">盖章版合同文本</label>
										<div class="layui-input-block">
											<div class="layui-upload">
												<button type="button" class="layui-btn" id="3-upload-more">上传</button>
												<div class="layui-upload-list" id="3-upload-more-list">
												</div>
											</div>
										</div>
									</div>
									<div class="layui-form-item">
										<label class="layui-form-label">其他附件</label>
										<div class="layui-input-block">
											<div class="layui-upload">
												<button type="button" class="layui-btn" id="4-upload-more">上传</button>
												<div class="layui-upload-list" id="4-upload-more-list">
												</div>
											</div>
										</div>
									</div>
								</div>
							</fieldset>
						</div>
					</div>
				</div>

				<div class="layui-form-item"
					style="position: fixed ! important; right: 30px; bottom: 45%; z-index: 10000;">
					<div class="layui-input-block">
						<button
							class="layui-btn layui-bg-blue layui-btn-normal layui-btn-lg  layui-btn-radius"
							type="button" lay-submit lay-filter="addInfo_form_submit"
							id="addInfo_form_submit">
							<i class="layui-icon layui-icon-ok layuiadmin-button-btn"></i> 提交
						</button>
					</div>
				</div>
			</form>
		</div>
	</div>
</body>
</html>
<script type="text/javascript"  >
String.prototype.format = function () {
	var model = arguments;
    return this.replace(/\{(\d+)\}/g, function (s, i) { 
        return model[i];
    });
}
String.prototype.toInt = function () {
	if(this==''){
		return 0;
	}
	return parseInt(this);
}
String.prototype.toFloat = function () {
	if(this==''){
		return 0;
	}
	return parseFloat(this);
}
Number.prototype.toMoney = function () {
	var m = Math.pow(10, 2);
	return Math.round(this * m) / m;
}
var getPercentage = function(a, b, d) {
	var quotient = Number(b) != 0 ? a / b : 0;
	if (d == true) {
		return setDecimalPlaces((1 - quotient) * 100, 2);
	}
	return setDecimalPlaces(quotient * 100, 2);
}

var setDecimalPlaces = function(f, digit) {
	var m = Math.pow(10, digit);
	return Math.round(f * m) / m;
}
		
function parentGroup($, type, id,area) {
	if (type == 'projectamountbefore' || type == 'outdiscount') {
		amountParentGroup($, 'projectamountbefore', id,area);
		countTopRows($, [ 'projectamountbefore'], area);
		outdiscountParentGroup($, id, area);
	}
	if (type == 'outdiscount') {
		amountParentGroup($, 'outdiscount', id,area);
		countTopRows($, [ 'projectamountbefore'], area);
		outdiscountParentGroup($, id, area);
	}
	if (type == 'totalpackageamountbefore' || type == 'indiscount') {
		amountParentGroup($, 'totalpackageamountbefore', id,area);
		countTopRows($, [ 'totalpackageamountbefore','inamountafter' ], area);
		indiscountParentGroup($, id, area);
	}
	if (type == 'indiscount') {
		amountParentGroup($, 'indiscount', id,area);
		countTopRows($, [ 'totalpackageamountbefore','inamountafter' ], area);
		indiscountParentGroup($, id, area);
	}
}

function amountParentGroup($, type, id,area) {
	var arr = id.split('.');	
	if (arr.length == 3 && type=="projectamountbefore") {		
		var item = arr.slice(0, 2);
		var trId = item.join('.');
				
		var $tr = $('[id="' + trId + '"]');
		$tr.find('.' + type).val($("tr[id^='" + trId + ".'][level=3]").find('.' + type).inputTotal());
		
		var projectTwo = $("tr[id^='" + trId + ".'][level=3]").find('.projectamountbefore').inputTotal();
		var length = $("tr[id^='" + trId + ".'][level=3]").find('.projectamountbefore').length;
		var sum = 0;
		for(var i = 1;i <= length;i++){
			var out = $("tr[id^='" + trId +"."+i+"'][level=3]").find('.outdiscount').val();
			var project = $("tr[id^='" + trId +"."+i+"'][level=3]").find('.projectamountbefore').val();
			sum += project*(1-out/100); 
		}
		if(projectTwo != 0){
			var num = ((1-(sum/projectTwo))*100).toFixed(2);
			$tr.find('.outdiscount').val(num);
		}else{
			$tr.find('.outdiscount').val(0);
		}
	}
	if (arr.length == 3 && type=="totalpackageamountbefore") {		
		var item = arr.slice(0, 2);
		var trId = item.join('.');
				
		var $tr = $('[id="' + trId + '"]');
		$tr.find('.' + type).val($("tr[id^='" + trId + ".'][level=3]").find('.' + type).inputTotal());
		var after = $("tr[id^='" + trId + ".'][level=3]").find('.inamountafter').inputTotal();
		$tr.find('.inamountafter').val(after);
		
		var afters = $("tr[id^='" + trId + ".'][level=3]").find('.inamountafter').inputTotal();
		var totalpackage = $("tr[id^='" + trId + ".'][level=3]").find('.totalpackageamountbefore').inputTotal();
		if(totalpackage != 0){
			var num = ((1-(afters/totalpackage))*100).toFixed(2);
			$tr.find('.indiscount').val(num);
		}else{
			$tr.find('.indiscount').val(0);
		}
	}
	if (arr.length == 3 && type=="outdiscount") {		
		var item = arr.slice(0, 2);
		var trId = item.join('.');
				
		var $tr = $('[id="' + trId + '"]');
		var projectTwo = $("tr[id^='" + trId + ".'][level=3]").find('.projectamountbefore').inputTotal();
		var length = $("tr[id^='" + trId + ".'][level=3]").find('.projectamountbefore').length;
		var sum = 0;
		for(var i = 1;i <= length;i++){
			var out = $("tr[id^='" + trId +"."+i+"'][level=3]").find('.outdiscount').val();
			var project = $("tr[id^='" + trId +"."+i+"'][level=3]").find('.projectamountbefore').val();
			sum += project*(1-out/100); 
		}
		if(projectTwo != 0){
			var num = ((1-(sum/projectTwo))*100).toFixed(2);
			$tr.find('.outdiscount').val(num);
		}else{
			$tr.find('.outdiscount').val(0);
		}
	}
	if (arr.length == 3 && type=="indiscount") {		
		var item = arr.slice(0, 2);
		var trId = item.join('.');
				
		var $tr = $('[id="' + trId + '"]');
		var afters = $("tr[id^='" + trId + ".'][level=3]").find('.inamountafter').inputTotal();
		var totalpackage = $("tr[id^='" + trId + ".'][level=3]").find('.totalpackageamountbefore').inputTotal();
		if(totalpackage != 0){
			var num = ((1-(afters/totalpackage))*100).toFixed(2);
			$tr.find('.indiscount').val(num);
		}else{
			$tr.find('.indiscount').val(0);
		}
	}
}

function countTopRows($, types, $area) {
	var $contractListLayuiRow = $area.find('.layui-row');
	$contractListLayuiRow.each(function() {		
		var id = $(this).attr('id');
		types.forEach(function(e) {
			if(e=='projectamountbefore'||e=='totalpackageamountbefore'||e=='inamountafter'){
				var $total =$("tr[id='" + id + "Row-1'] input[type=text]." + e);						
				var total = $("tr[id^='sub" + id + "Row-1.'][level=2] input[type=text]." + e).inputTotal();
				$total.val(total);
			}			
		});
	});
	
	types.forEach(function(e) {
		if(e=='projectamountbefore'||e=='totalpackageamountbefore'||e=='inamountafter'){
			var $total = $('#' + e);
			var total = $contractListLayuiRow.find("tr[id$='Row-1'] input[type=text]." + e).inputTotal();
			$total.val(total);
		}
	});
}


function outdiscountParentGroup($, id, $area) {
	var $contractListLayuiRow = $area.find('.layui-row');
	/* 对外下浮率（%）=1-合计【项目合同对外建安二级费用（下浮前）*（1-对外下浮率）】/子项项目合同对外建安费（下浮前） */
	var arr = id.split('.');
	var trId = arr[0].replace('sub', '');
	
	var sumAfter = function(selector){
		var sum = 0;
		$contractListLayuiRow.find("tr[id*='"+selector+"'][level=2]").each(function(){
			var _amountBefore = $(this).find('.projectamountbefore').val().toFloat();
			var _discount = $(this).find('.outdiscount').val().toFloat();									
			var _amountAfter = (_amountBefore) * (1 - _discount / 100);
			sum = setDecimalPlaces(sum + _amountAfter, 2);
		});
		return sum;
	}
	
	var discount = function($tr) {		
		if ($tr) {
			var $amountBefore = $tr.find(".projectamountbefore");
			var $discount = $tr.find(".outdiscount");
			var amountBefore = $amountBefore.val();
			var amountAfter = sumAfter(trId+'.');
			
			var discount = getPercentage(amountAfter, amountBefore, true);
			$discount.val(discount);
		}
	}
	
	discount($('#' + trId));
	
	/* 1-合计所有子项【项目合同对外建安二级费用（下浮前）*（1-对外下浮率）】/合计所有子项项目合同对外建安费（下浮前）*/
	var amountBefore = $contractListLayuiRow.find("tr[id$='Row-1']").find('.projectamountbefore').inputTotal(), 
	    amountAfter = sumAfter('Row-1.');	
	var discount = getPercentage(amountAfter, amountBefore, true);
	$('#outdiscount').val(discount);
}


function indiscountParentGroup($, id,$area) {
	var $contractListLayuiRow = $area.find('.layui-row');
	/* 对内下浮率（%）=1-子项对内合同价（下浮后）/子项总包合同对外建安费（下浮前） */
	var discount = function($tr) {
		if ($tr) {
			var $amountBefore = $tr.find(".totalpackageamountbefore");
			var $amountAfter = $tr.find(".inamountafter");
			var $discount = $tr.find(".indiscount");
			var amountBefore = $amountBefore.val();
			var amountAfter = $amountAfter.val();
			var discount = getPercentage(amountAfter, amountBefore, true);
			$discount.val(discount);
		}
	}
	var arr = id.split('.');
	var trId = arr[0].replace('sub', '');
	discount($('#' + trId));	
	/* 1-所有子项对内合同价（下浮后）/所有总包合同子项对外建安费（下浮前）*/
	var amountBefore = $contractListLayuiRow.find("tr[id$='Row-1']").find('.totalpackageamountbefore').inputTotal(), 
	    amountAfter = $contractListLayuiRow.find("tr[id$='Row-1']").find('.inamountafter').inputTotal();	
	var discount = getPercentage(amountAfter, amountBefore, true);
	$('#indiscount').val(discount);
	/*新加的代码添到最后一行*/
    overallDownfloatingRate($,amountBefore,amountAfter,discount);
}

function overallDownfloatingRate($,priceBefore,priceAfter,discount){
    var $preTotalSumId = $("#preTotalSumId")
    ,$afterTotalSumId = $("#afterTotalSumId")
    ,$totalRateId =  $("#totalRateId");                
    
    $preTotalSumId.val(priceBefore);
    $afterTotalSumId.val(priceAfter);
    $totalRateId.val(discount);                
}

	var subList = [];
	var proName;
	var proNameid;
	//静态资源路径前缀
	var staticPath = '${fileHttpPre}';
	var stateJSON = <infopub:dicJson groupNo="A00010028" />;
	layui.config({
				base : '${ctx}/resources/layuiadmin/' //静态资源所在路径
			})
			.extend({
				index : 'lib/index' //主入口模块
			})
			.use([ 'index', 'set', 'upload', 'element', 'laydate' ],
					function() {
						var $ = layui.$, form = layui.form, element = layui.element, laydate = layui.laydate, upload = layui.upload;
						// 正则校验
						form.verify({
							//验证汉字
						    CHS:[
						    	/^[\u0391-\uFFE5]+$/
						    	,'只能输入汉字'
						  	],
						  	//名字校验
						  	COC: [
								/^[\u4e00-\u9fa5_a-zA-Z0-9]+$/
								,'请输入正确的名称'
						  	],
						  	//大于0的正整数
						  	intNumber:[
								/^[1-9]\d*$/
								,'请输入正确的数字'
						  	],
						  	//数字只能有两位小数
						  	floatNumber:[
								/^([-]?)([0-9](\d+)?(\.\d{1,2})?$)|(^\d\.\d{1,2}$)/
								,'请输入正确的数字'
						  	],
						  	telNumber:[/^[1][3,4,5,7,8,9][0-9]{9}$/
								  		,'请输入正确的号码'
							],
						  	//数字大于0，并只能有两位小数
						  	floatAmount:[
								/^([0-9](\d+)?(\.\d{1,2})?$)|(^\d\.\d{1,2}$)/
								//var pattern=/^((\d+\.\d*[1-9]\d{1})|(\d*[1-9]\d*\.\d{2}))$/; 
								,'请输入正确的数字'
						  	]
						});
						
						var fileFormatWord = 'application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document';
						var fileFormatPdf = 'application/pdf';
						var fileFormat = 'application/zip,application/x-rar-compressed,image/jpeg,image/png,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.ms-powerpoint,application/vnd.openxmlformats-officedocument.presentationml.presentation,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/pdf';
						uploadRender(1, upload,fileFormatWord, $);
						uploadRender(2, upload,fileFormatPdf, $);
						uploadRender(3, upload,fileFormat, $);
						uploadRender(4, upload,fileFormat, $);
						laydate.render({
							elem : '#id_supplementaryAgreementSigningDate',
							trigger : 'click'
						});
						laydate.render({
							elem : '#id_contractCompletionDate',
							trigger : 'click'
						});	
						laydate.render({
							elem : '#id_adjustedCompletionDate',
							trigger : 'click'
						});	
						laydate.render({
							elem : '#id_practicalCompletionDate',
							trigger : 'click'
						});
						checkValueVerifyBeginBuildDate(laydate, $);
						checkValueVerifyActBeginDate(laydate, $);
						(function($) {
							$.fn.inputTotal = function() {
								var sum = 0;
								this.each(function() {
									var thisNum = $(this);
									var val = !!thisNum.val() ? thisNum.val()
											: 0;
									var num = parseFloat(val);
									sum = setDecimalPlaces(sum + num, 2);
								});
								return sum;
							};
						})($);
						var $contractList = $('.contract-list');						
						$contractList.on('click','.del-layui-row',function(){
							var $layrow = $(this).parents('.layui-row');	
							if($contractList.find('.layui-row').length==1){
								return layer.msg('至少需保留一个子项', {icon: 1});
							}
							layui.layer.confirm('确定删除子项？', {
										icon : 3,
										title : '提示'
									},function(index) {
										$layrow.remove();	
										layui.layer.close(index);
										countTopRows($, ['projectamountbefore','totalpackageamountbefore','outdiscount','indiscount','inamountafter'],$contractList);
										
										var $tr =$('.layui-row .contract-money input[type=text]:not([readonly].decimal)');
										var $parentTr = $tr.parents('tr');
										var id = $parentTr.prop("id");
										outdiscountParentGroup($, id, $contractList);
										indiscountParentGroup($, id, $contractList);
							});							
							
							
						}).on('click', '.add-new-row', function() {
							addNewRow(this);
						}).on('click', '.add-sub-row', function() {
							addSubRow(this);
						}).on('click', '.del-sub-row', function() {
							deleteSubRow(this);
						}).on('keyup','.decimal', function() {
									var val = this.value.replace(
											/^(\-)*(\d+)\.(\d\d).*$/,
											'$1$2.$3');
									var val2 = val.replace(/[^0-9.]/g,
											"");
									this.value = val2;
								})
						.on('blur','.layui-row .contract-money input[type=text]:not([readonly].decimal)',
								function() {
									var $tr = $(this).parents('tr');
									var type, id;
									type = $(this).prop('class')
											.replace('layui-input', '')
											.replace('decimal', '')
											.trim();
									id = $tr.prop("id");
									if(!$(this).hasClass("outdiscount") && !$(this).hasClass("indiscount") && !$(this).hasClass("typeNames")){
										arabiaToCN(this,1);
									}
									if(type=='totalpackageamountbefore'||type=='indiscount'){
										var $amountBefore = $tr.find(".totalpackageamountbefore");
										var $amountAfter = $tr .find(".inamountafter");
										var $discount = $tr .find(".indiscount");										
										var amountBefore = $amountBefore .val().toFloat();
										var discount = $discount.val().toFloat();										
										var amountAfter = amountBefore * (1 - discount / 100);
										
										$amountAfter.val(amountAfter.toMoney());										
									}
									parentGroup($, type, id,$contractList);
						}).on('blur','.layui-row input.subNames',function(){
							var $this = $(this);
							var $itemNameSubInputs = $this.parents('div.layui-row').find('input.itemNameSub');
							$itemNameSubInputs.val(this.value);																
						});
						

						planRateDataBind($);
				
						form.on('select(add_select_proId)', function(data) {
							var id = data.value;
							proNameid = data.value;
							proName = data.elem.getAttribute('proName');
														
							if(id==''||id==null){
					    		layer.msg('请选择项目名称',{icon: 1});
					    		return;
					    	}else{
					    		getContractExtByProId(id); 
					    	} 
						});

						form.on('submit(addInfo_form_submit)', function(data) {
							$("#addInfo_form_submit").removeAttr("lay-submit").removeClass("layui-bg-blue").addClass("layui-btn-disabled");
							//提交 Ajax 成功后，静态更新表格中的数据
		                   	
		                   	$.ajax({
		                       	type : 'post',
		            			url : basePath + '/innerAgrt/save',
		                       	data: $('#addInfo_form').serialize(),
		            			success:function(result){
		            				if(result.success){
		            					layer.closeAll('loading'); //关闭loading
		            					layer.msg('提交单据成功~',{icon: 1});
		            					//两秒后关闭当前页面
		            					setTimeout(function(){
		            						/**
		            						 * 查找父菜单，并刷新
		            						 */
		            						var topDoc = $(window.top.document);
		            						var path = basePath + '/innerAgrt/list';
		            						// 获取页面名称
		            						var name = topDoc.find(".layui-nav-item [lay-href^='" + path + "']").text();
		            						if(name == '' || name == null){
		            							name = '内部协议补充合同';
		            						}
		            						window.parent.layui.index.openTabsPage(path, name);
		            						var iframe = window.parent.layui.admin.tabsBody(window.parent.layui.admin.tabsPage.index).find(".layadmin-iframe");
		            						iframe[0].contentWindow.location.reload(true);
		            						
		            						/**
		            						 * 关闭当前页
		            						 */
		            						var currPath = basePath + '/innerAgrt/add';
		            						var layid = topDoc.find("li[lay-id^='" + currPath + "']").attr('lay-id');
		            						window.parent.layui.element.tabDelete('layadmin-layout-tabs', layid);//关闭当前页
		            				        }, 2000);
		            				}else{
		            					layer.closeAll('loading'); //关闭loading
		              					$("#addInfo_form_submit").removeClass("layui-btn-disabled").addClass("layui-bg-blue").attr("lay-submit","");
		            					layer.msg(result.msg,{icon: 7});
		            			  	}
		            			}
		                   	});
						});
					});

var  planRateDataBind=function($){	
	var planRateData=[{lowerLimit:0,upperLimit:0,proportion:0}];	
	var $table=$('#plan-rate').find('tbody'); $table.empty();
	$table.on('click','.add-row',function(){						
		var $row = $(this).parents('tr');
		var html=[],rowId= parseInt($row.find('.label').text())+1;					
		html.push('<tr id="PLANRATERow-'+rowId+'"  >');
		html.push('<td><span class="label" style="text-align:center;">'+rowId+'</span><input type="hidden" value="'+rowId+'" name="showIdxs" /></td>');
		html.push('<td><input type="text" value="0" id="minValueId'+rowId+'" name="minValues" lay-verify="required|floatNumber" autocomplete="off" class="layui-input decimal lowerLimit" /></td>');
		html.push('<td><input type="text" value="0" id="maxValueId'+rowId+'" name="maxValues" lay-verify="required|floatNumber" autocomplete="off" class="layui-input decimal upperLimit" /></td>');
		html.push('<td><input type="text" value="0" id="payRateId'+rowId+'" name="payRates" lay-verify="required|floatNumber" autocomplete="off" class="layui-input decimal proportion" /></td>');
		html.push('<td class="tg-c" >');
		html.push('<button type="button" class="layui-btn layui-btn-sm del-row" ><i class="layui-icon">&#xe640;</i></button>');														
		html.push('<button type="button" class="layui-btn layui-btn-sm add-row" ><i class="layui-icon">&#xe654;</i></button></td>');							
		html.push('</tr>');
		var $newRow = $(html.join(''));
		$row.after($newRow);
	
		var newIndex = $newRow.index(); 
		$table.find('tr:gt('+newIndex+')').each(function(){
			var $row = $(this);
			var rowId= parseInt($row.find('.label').text())+1;
			$row.find('.label').text(rowId).end().find('input[type=hidden]').val(rowId);				
		});
		
	}).on('click','.del-row',function(){						
		var $row = $(this).parents('tr');var index = $row.index()-1;
		$row.remove();
		 
		$table.find('tr:gt('+index+')').each(function(){
			var $row = $(this);
			var rowId= parseInt($row.find('.label').text())-1;
			$row.find('.label').text(rowId).end().find('input[type=hidden]').val(rowId);				
		});
	}).on('keyup','.decimal',
			function() {
				var val = this.value.replace(
						/^(\-)*(\d+)\.(\d\d).*$/,
						'$1$2.$3');
				var val2 = val.replace(/[^0-9.]/g,
						"");
				this.value = val2;
			});
	
	for(var i=0,j=planRateData.length;i<j;i++){
		var html=[],rowId=i+1;
		var item = planRateData[i];
		html.push('<tr id="PLANRATERow-'+rowId+'"  >');
		html.push('<td  class="tg-c" ><span class="label" style="text-align:center;">'+rowId+'</span><input type="hidden" value="'+rowId+'" name="showIdxs" /></td>');
		html.push('<td><input type="text" value="'+item.lowerLimit+'" name="minValues" lay-verify="required|floatNumber" autocomplete="off" class="layui-input decimal lowerLimit" /></td>');
		html.push('<td><input type="text" value="'+item.upperLimit+'" name="maxValues" lay-verify="required|floatNumber" autocomplete="off" class="layui-input decimal upperLimit" /></td>');
		html.push('<td><input type="text" value="'+item.proportion+'" name="payRates" lay-verify="required|floatNumber" autocomplete="off" class="layui-input decimal proportion" /></td>');
		html.push('<td class="tg-c" >');
		if(i>0){
			html.push('<button type="button" class="layui-btn layui-btn-sm del-row"   ><i class="layui-icon">&#xe640;</i></button>');								
		}							
		html.push('<button type="button" class="layui-btn layui-btn-sm add-row" ><i class="layui-icon">&#xe654;</i></button></td>');							
		html.push('</tr>');	
		$table.append(html.join(''));
	}	
}

	var uploadRender = function(id, upload,fileFormat, $) {
		upload
				.render({
					elem : '#' + id + '-upload-more',
					url : basePath + '/innerAgrt/uploadAtt/',
					data : {
						types : id
					},
					multiple : true,
					accept : 'file',
					acceptMime : fileFormat,
					before : function(obj) {
						layer.load();
					},
					done : function(res) {
						if (res.code > 0) {
							layer.closeAll('loading');
							return layer.msg(res.msg, {
								icon : 7
							});
						}
						if (res.entity != null && res.entity.length > 0) {
							for ( var i in res.entity) {
								var preProject = res.entity[i];
								var arr = preProject.split("|");
								var imgSrc = "";
								var suffix = arr[1].substring(arr[1]
										.lastIndexOf(".") + 1, arr[1].length);
								if (suffix == 'jpg' || suffix == 'png') {
									imgSrc = "${fileHttpPre}/" + arr[3];
								} else {
									imgSrc = "${ctx}/resources/images/"
											+ suffix + ".jpg";
								}
								$('#' + id + '-upload-more-list')
										.append(
												'<div class="layui-upload-img-div" id="upload_img_'+arr[2]+'"><img src="'+imgSrc+'" title="'+ arr[1] +'" class="layui-upload-img"><div class="mask"><a href="javascript:void(0)" onclick="showImg(\''
														+ "${fileHttpPre}"
														+ arr[3]
														+ '\');">查看</a><a href="javascript:void(0)" onclick="del(\''
														+ arr[2]
														+ '\')";>删除</a></div><p>'
														+ arr[1]
														+ '</p><input type="hidden" value="'+preProject+'" id="fileAtt_'+arr[2]+'" name="fileAtts'+id+'" ></input></div>');
							}
						}
					},
					allDone : function(obj) {
						layer.closeAll('loading');
					},
					error : function() {
						layer.closeAll('loading');
						layer.msg("上传失败，请稍后再试~", {
							icon : 7
						});
					}
				});
	}
	//删除文件
	function del(index) {
		layui.$("#fileAtt_" + index).remove();
		layui.$("#upload_img_" + index).remove();
	}

	//根据url查看文件
	function showImg(url) {
		var openWin = window.open(url,'','left=410,height=768, width=1024, top=200,  toolbar=no, menubar=no, scrollbars=no, resizable=no,location=no, status=no');
	}
	
	//根据交底pk带出交底需要的字段
	function getContractExtByProId(id) {
		var $ = layui.$, form = layui.form
		var templateLayuiRowHtml = $('#layui-row').html();
		var $contractList = $('.contract-list');
		$contractList.find(".layui-row").remove();
		
		$.ajax({
			type : "POST", //提交方式  
			url : "${ctx}/innerAgrt/getInnerAgrtByProCode",//路径  
			data : { "proCodeAndCodes" : id
			},//数据，这里使用的是Json格式进行传输  
			success : function(result) {//返回数据根据结果进行相应的处理 
							
				if (result.flag == true &&  !!result.innerAgrtProCode==true) {
					//项目名称带出内部协议基础信息
					$("#id_proCode")
						.attr("value", result.innerAgrtProCode.proCode);//项目编号
					if (result.innerAgrtProCode.orgAreaName != null) {
						$("#id_regionalCompany").attr("value",
								result.innerAgrtProCode.orgAreaName);//区域公司
						$("#areaId").attr("value",
								result.innerAgrtProCode.hrOrgAreaId);//区域公司id
					} else {
						$("#id_regionalCompany").attr("value", "暂时为空不可编辑");//区域公司
					}
					if (result.innerAgrtProCode.orgProName != null) {
						$("#id_projectCompany").attr("value", result.innerAgrtProCode.orgProName);//项目公司
						$("#compId").attr("value", result.innerAgrtProCode.hrOrgProId);
					} else {
						$("#id_projectCompany").attr("value", "暂时为空不可编辑");//项目公司
		
					}
					$("#id_ImplementingBody").attr("value",
							result.innerAgrtProCode.carryOrg);//实施机构
					$("#id_projectLeader").attr("value",
							result.innerAgrtProCode.proLeader);//项目负责人
					$("#id_projectAddress").attr("value",
							result.innerAgrtProCode.sgCityName);//项目地址
					$("#sgCityId").attr("value",
							result.innerAgrtProCode.sgCityId);//项目城市id		
					$("#id_internalAgreementName").attr("value",
							result.innerAgrtProCode.innerAgrtName);//内部协议名称
					$("#id_contractUnitName").attr("value",
							result.innerAgrtProCode.sgCoopName);//合同单位名称
					$("#sgCoopId").attr("value",
							result.innerAgrtProCode.sgCoopId);//合同单位id
							
					//项目名称带出内部协议的合同信息	
					$("#id_Contractconstructionperiodyear").attr("value", result.innerAgrtProCode.periodYears);//合同工期（年）	
					
					$("#id_Contractoperationperiodyear").attr("value",result.innerAgrtProCode.periodDays);//合同工期(天)
					
					//合同开工日期									
					if (result.innerAgrtProCode.beginBuildDate != null) {
						var beginBuildDate = layui.util.toDateString(result.innerAgrtProCode.beginBuildDate,"yyyy-MM-dd");
						
						$("#id_contractCommencementDate").attr("value",beginBuildDate);
					} else {
						$("#id_contractCommencementDate").attr("value", "合同开工日期为空");
		
					}
					//计算合同竣工日期
					if (result.innerAgrtProCode.endBuildDate != null) {
						var endBuildDate = layui.util.toDateString(result.innerAgrtProCode.endBuildDate,"yyyy-MM-dd");					
						$("#id_contractCompletionDate").attr("value",endBuildDate);
					} else {
						$("#id_contractCompletionDate").attr("value", "合同竣工日期为空");
		
					}
					//实际开工日期									
					if (result.innerAgrtProCode.actBeginDate != null) {
						var actBeginDate = layui.util.toDateString(result.innerAgrtProCode.actBeginDate,"yyyy-MM-dd");
						$("#id_actualCommencementDate").attr("value",actBeginDate);
					} else {
						$("#id_actualCommencementDate").attr("value", "实际开工日期为空");
		
					}
					//计算调整后竣工日期
					if (result.innerAgrtProCode.adjustEndDate != null) {
						var adjustEndDate = layui.util.toDateString(result.innerAgrtProCode.adjustEndDate,"yyyy-MM-dd");
						$("#id_adjustedCompletionDate").attr("value",adjustEndDate);
					} else {
						$("#id_adjustedCompletionDate").attr("value", "调整后竣工日期为空");
		
					}
					//实际竣工日期									
					if (result.innerAgrtProCode.actEndDate != null) {
						var actEndDate = layui.util.toDateString(result.innerAgrtProCode.actEndDate,"yyyy-MM-dd");
						$("#id_practicalCompletionDate").attr("value",actEndDate);
					} else {
						$("#id_practicalCompletionDate").attr("value", "实际竣工日期为空");
		
					}
					$("#id_priceAdjustmentMethod").html(
							result.innerAgrtProCode.qaStandard);//质量标准
					$("#prePayRateId").attr("value",
							result.innerAgrtProCode.prePayRate);//预付款比例(%)
					$("#monthPayRateId").attr("value",
							result.innerAgrtProCode.monthPayRate);//月度付款比例(%)
					$("#yearPayRateId").attr("value",
							result.innerAgrtProCode.yearPayRate);//年度付款比例(%)
					$("#checkAfterRateId").attr("value",
							result.innerAgrtProCode.checkAfterRate);//竣工验收后付款比例(%)					
					$("#settleAfterRateId").attr("value",
							result.innerAgrtProCode.settleAfterRate);//结算后付款比例(%)
					$("#qaEnsureRateId").attr("value",
							result.innerAgrtProCode.qaEnsureRate);//质保金比例(%)
					
					$("#midFeeOrgNameId").html('');
					$("#workersOrgNameId").html('');
					$("#bondOrgNameId").html('');
					var midFeeOrgName = "";
					midFeeOrgName += '<option value="" >请选择</option>';
					if($("#compId").val()!=null&&$("#compId").val()!=''){
						if(result.innerAgrtProCode.orgProName==result.innerAgrtProCode.midFeeOrgName){												
							midFeeOrgName += '<option value='+result.innerAgrtProCode.orgProName+' selected>'+result.innerAgrtProCode.orgProName+'</option>';
							midFeeOrgName += '<option value='+result.innerAgrtProCode.sgCoopName+'>'+result.innerAgrtProCode.sgCoopName+'</option>';
							midFeeOrgName += '<option value="无">无</option>';
						}else if(result.innerAgrtProCode.sgCoopName==result.innerAgrtProCode.midFeeOrgName){						
							midFeeOrgName += '<option value='+result.innerAgrtProCode.orgProName+'>'+result.innerAgrtProCode.orgProName+'</option>';
							midFeeOrgName += '<option value='+result.innerAgrtProCode.sgCoopName+' selected>'+result.innerAgrtProCode.sgCoopName+'</option>';
							midFeeOrgName += '<option value="无">无</option>';
						}else if(result.innerAgrtProCode.midFeeOrgName=='无'){
							midFeeOrgName += '<option value='+result.innerAgrtProCode.orgProName+'>'+result.innerAgrtProCode.orgProName+'</option>';
							midFeeOrgName += '<option value='+result.innerAgrtProCode.sgCoopName+'>'+result.innerAgrtProCode.sgCoopName+'</option>';
							midFeeOrgName += '<option value="无" selected>无</option>';
						}
					}else{
						if(result.innerAgrtProCode.sgCoopName==result.innerAgrtProCode.midFeeOrgName){
							midFeeOrgName += '<option value='+result.innerAgrtProCode.sgCoopName+' selected>'+result.innerAgrtProCode.sgCoopName+'</option>';
						}else if(result.innerAgrtProCode.midFeeOrgName=='无'){
							midFeeOrgName += '<option value='+result.innerAgrtProCode.sgCoopName+'>'+result.innerAgrtProCode.sgCoopName+'</option>';
							midFeeOrgName += '<option value="无" selected>无</option>';
						}
					}
					$("#midFeeOrgNameId").append(midFeeOrgName);//居间费承担方
					
					var workersOrgName = "";
					workersOrgName += '<option value="" >请选择</option>';
					if($("#compId").val()!=null&&$("#compId").val()!=''){
						if(result.innerAgrtProCode.orgProName==result.innerAgrtProCode.workersOrgName){												
							workersOrgName += '<option value='+result.innerAgrtProCode.orgProName+' selected>'+result.innerAgrtProCode.orgProName+'</option>';
							workersOrgName += '<option value='+result.innerAgrtProCode.sgCoopName+'>'+result.innerAgrtProCode.sgCoopName+'</option>';
							workersOrgName += '<option value="无">无</option>';
						}else if(result.innerAgrtProCode.sgCoopName==result.innerAgrtProCode.workersOrgName){						
							workersOrgName += '<option value='+result.innerAgrtProCode.orgProName+'>'+result.innerAgrtProCode.orgProName+'</option>';
							workersOrgName += '<option value='+result.innerAgrtProCode.sgCoopName+' selected>'+result.innerAgrtProCode.sgCoopName+'</option>';
							workersOrgName += '<option value="无">无</option>';
						}else if(result.innerAgrtProCode.workersOrgName=='无'){
							workersOrgName += '<option value='+result.innerAgrtProCode.orgProName+'>'+result.innerAgrtProCode.orgProName+'</option>';
							workersOrgName += '<option value='+result.innerAgrtProCode.sgCoopName+'>'+result.innerAgrtProCode.sgCoopName+'</option>';
							workersOrgName += '<option value="无" selected>无</option>';
						}
					}else{
						if(result.innerAgrtProCode.sgCoopName==result.innerAgrtProCode.workersOrgName){
							workersOrgName += '<option value='+result.innerAgrtProCode.sgCoopName+' selected>'+result.innerAgrtProCode.sgCoopName+'</option>';
							workersOrgName += '<option value="无">无</option>';
						}else if(result.innerAgrtProCode.workersOrgName=='无'){
							workersOrgName += '<option value='+result.innerAgrtProCode.sgCoopName+'>'+result.innerAgrtProCode.sgCoopName+'</option>';
							workersOrgName += '<option value="无" selected>无</option>';
						}
					}
					$("#workersOrgNameId").append(workersOrgName);//农民工保证金承担方
					
					var bondOrgName = "";
					bondOrgName += '<option value="" >请选择</option>';
					if($("#compId").val()!=null&&$("#compId").val()!=''){
						if(result.innerAgrtProCode.orgProName==result.innerAgrtProCode.bondOrgName){												
							bondOrgName += '<option value='+result.innerAgrtProCode.orgProName+' selected>'+result.innerAgrtProCode.orgProName+'</option>';
							bondOrgName += '<option value='+result.innerAgrtProCode.sgCoopName+'>'+result.innerAgrtProCode.sgCoopName+'</option>';
							bondOrgName += '<option value="无">无</option>';
						}else if(result.innerAgrtProCode.sgCoopName==result.innerAgrtProCode.bondOrgName){						
							bondOrgName += '<option value='+result.innerAgrtProCode.orgProName+'>'+result.innerAgrtProCode.orgProName+'</option>';
							bondOrgName += '<option value='+result.innerAgrtProCode.sgCoopName+' selected>'+result.innerAgrtProCode.sgCoopName+'</option>';	
							bondOrgName += '<option value="无">无</option>';
						}else if(result.innerAgrtProCode.bondOrgName=='无'){
							bondOrgName += '<option value='+result.innerAgrtProCode.orgProName+'>'+result.innerAgrtProCode.orgProName+'</option>';
							bondOrgName += '<option value='+result.innerAgrtProCode.sgCoopName+'>'+result.innerAgrtProCode.sgCoopName+'</option>';
							bondOrgName += '<option value="无" selected>无</option>';
						}
					}else{
						if(result.innerAgrtProCode.sgCoopName==result.innerAgrtProCode.bondOrgName){
							bondOrgName += '<option value='+result.innerAgrtProCode.sgCoopName+' selected>'+result.innerAgrtProCode.sgCoopName+'</option>';
						}else if(result.innerAgrtProCode.bondOrgName=='无'){
							bondOrgName += '<option value='+result.innerAgrtProCode.sgCoopName+'>'+result.innerAgrtProCode.sgCoopName+'</option>';
							bondOrgName += '<option value="无" selected>无</option>';
						}
					}
					$("#bondOrgNameId").append(bondOrgName);//履约保函承担方

					//项目名称带出综合计划完成率对应月度付款比例
					$("#assessPlanFlagId").html('');
				      var strAssessPlanFlagBuffer = ""; 
				      if(result.innerAgrtProCode.assessPlanFlag != null){//是否纳入综合计划考核
				        if(result.innerAgrtProCode.assessPlanFlag=='0'){
				        	strAssessPlanFlagBuffer+= '<option value='+0+' selected>否</option>';
				        	strAssessPlanFlagBuffer+= '<option value='+1+'>是</option>';
				        }else if(result.innerAgrtProCode.assessPlanFlag=='1'){
				        	strAssessPlanFlagBuffer+= '<option value='+1+'>是</option>';
				        	strAssessPlanFlagBuffer+= '<option value='+0+' selected>否</option>';
				        }
				      }
				     $("#assessPlanFlagId").append(strAssessPlanFlagBuffer);
						var innerAgrtRate = result.innerAgrtRateList;//接收综合计划完成率对应月度付款比例集合	
						var $table=$('#plan-rate').find('tbody'); $table.empty();
						layui.$.each(innerAgrtRate, function(i,item){
							var html=[],rowId=i+1;
							if(item.showIdx==rowId){
								html.push('<tr id="PLANRATERow-'+rowId+'"  >');
								html.push('<td  class="tg-c" ><span class="label" style="text-align:center;">'+rowId+'</span><input type="hidden" value="'+rowId+'" name="showIdxs" /></td>');
								html.push('<td><input type="text" value="'+item.minValue+'" id="minValueId'+rowId+'" name="minValues" lay-verify="required|floatNumber" autocomplete="off" class="layui-input decimal lowerLimit" /></td>');
								html.push('<td><input type="text" value="'+item.maxValue+'" id="maxValueId'+rowId+'" name="maxValues" lay-verify="required|floatNumber" autocomplete="off" class="layui-input decimal upperLimit" /></td>');
								html.push('<td><input type="text" value="'+item.payRate+'" id="payRateId'+rowId+'" name="payRates" lay-verify="required|floatNumber" autocomplete="off" class="layui-input decimal proportion" /></td>');
								html.push('<td class="tg-c" >');
								if(i>0){
									html.push('<button type="button" class="layui-btn layui-btn-sm del-row"   ><i class="layui-icon">&#xe640;</i></button>');								
								}							
								html.push('<button type="button" class="layui-btn layui-btn-sm add-row" ><i class="layui-icon">&#xe654;</i></button></td>');							
								html.push('</tr>');	
								$table.append(html.join(''));
							}									
			       	 	});		
							
					//项目名称带出项目合同的附件信息数据
					var innerAgrtAtt = result.innerAgrtAttList;//合同的附件信息集合
					$(".layui-upload-list").each(function(){
						var id = $(this).attr("id");
						$("#"+id).html('');
					});
					if(innerAgrtAtt.length > 0){
						layui.$.each(innerAgrtAtt, function(i,item){
							var imgSrc = "";
							var suffix = item.fileSuffix;
							if(suffix == '.jpg' || suffix == '.png'){
								imgSrc = "${fileHttpPre}/"+item.filePath;
							}else{
								imgSrc = "${ctx}/resources/images/"+suffix.substring(1)+".jpg";
							}
							$('#'+item.types+'-upload-more-list').append('<div class="layui-upload-img-div" id="upload_img_'+item.id+'"><img src="'+imgSrc+'" title="'+ item.fileName +'" class="layui-upload-img"><div class="mask"><a href="javascript:void(0)" onclick="showImg(\''+"${fileHttpPre}"+item.filePath +'\');">查看</a><a href="javascript:void(0)" onclick="del(\''+item.id+'\')";>删除</a></div><p>'+item.fileName+'</p><input type="hidden" value="'+item.types+"|"+item.fileName+item.fileSuffix+"|"+item.id+"|"+item.filePath+'" id="fileAtt_'+item.id+'" name="fileAtts'+item.types+'" ></input></div> ');
	                    });
					}
					//项目名称带出合同价款信息
					
					$('#preTotalSumId').val(result.innerAgrtProCode.preTotalSum);
					$('#afterTotalSumId').val(result.innerAgrtProCode.afterTotalSum);
					$('#totalRateId').val(result.innerAgrtProCode.totalRate);					
					$('#projectamountbefore').val(result.innerAgrtProCode.proContractPreSum);
					$('#totalpackageamountbefore').val(result.innerAgrtProCode.preTotalSum);					
					$('#outdiscount').val(result.innerAgrtProCode.outDownRate);
					$('#indiscount').val(result.innerAgrtProCode.innerDownRate);
					$('#inamountafter').val(result.innerAgrtProCode.afterTotalSum);
					
					var hash = {},subList=[];					
					for(var i = 0, j = result.innerAgrtDetailAndSubList.length; i < j; i++) {												
						var e = result.innerAgrtDetailAndSubList[i];						
						if(typeof(hash[e.agrtSubId])=='undefined'){
							hash[e.agrtSubId] = subList.length;							
							subList.push({
								subName:e.subName,
								agrtSubId:e.agrtSubId,
								list:[{
									subRowId : e.orderIdx.indexOf(',')!=-1?e.orderIdx.split(',')[1]:e.orderIdx,
									costType : e.typeName.indexOf(',')!=-1?e.typeName.split(',')[1]:e.typeName,
									projectamountbefore : e.proContractPreFee,
									totalpackageamountbefore : e.packPreFee,
									outdiscount : e.outDownRate,
									indiscount : e.innerDownRate,
									inamountafter : e.afterDownFee	
							}]});
						}else{								
							var index =  hash[e.agrtSubId].toString().toInt();
							subList[index].list.push({
								subRowId : e.orderIdx.indexOf(',')!=-1?e.orderIdx.split(',')[1]:e.orderIdx,
								costType : e.typeName.indexOf(',')!=-1?e.typeName.split(',')[1]:e.typeName,
								projectamountbefore : e.proContractPreFee,
								totalpackageamountbefore : e.packPreFee,
								outdiscount : e.outDownRate,
								indiscount : e.innerDownRate,
								inamountafter : e.afterDownFee
							});						
						}						
					}
					for (var i = 0, j = subList.length; i < j; i++) {
						var e = result.innerAgrtDetailAndSubList[i];						
						var itemNameSub = subList[i].subName,subId = subList[i].agrtSubId;
						var tempHtml = templateLayuiRowHtml.format(subId,itemNameSub);
						var $html = $(tempHtml);						
						subList[i].list.forEach(function(e){
							var subRowId = e.subRowId;
							var costType = e.costType;
							var projectamountbefore = e.projectamountbefore;
							var totalpackageamountbefore = e.totalpackageamountbefore;
							var outdiscount = e.outdiscount;
							var indiscount = e.indiscount;	
							var inamountafter = e.inamountafter;	
							
							var trid = subRowId.indexOf('.')!=-1?('tr[id="sub' + subId + 'Row-' + subRowId + '"]'):('tr[id="' + subId + 'Row-' + subRowId + '"]');
							var $row = $html.find('tr[id$="' + subId + 'Row-' + subRowId + '"]');
							if ($row.length == 1) {
								$row.find('input[type="hidden"]:eq(0)').val(subRowId);
								var $typeNames = $row.find('td:eq(1) input.typeNames');											
								if ($typeNames.val() != costType) {
									$typeNames.val(costType);
								}
								
								$row.find('td:eq(2) input').val(projectamountbefore);
								$row.find('td:eq(3) input').val(totalpackageamountbefore);
								$row.find('td:eq(4) input').val(outdiscount);
								$row.find('td:eq(5) input').val(indiscount);
								$row.find('td:eq(6) input').val(inamountafter);
															
							} else {							
								var arr = subRowId.split('.');
								var level = arr.length;
								
								if (level == 2) {				
									var id = "sub"+subId+"Row-"+subRowId;												
									var types = subRowId.split('.');        
							        var feeTypes = types[0],feeSmallTypes = types[0]+'.'+types[1];								        												
									var $trHtml = $($('#layui-row-tr').html().format(id,level,subRowId,subId,costType,feeTypes,feeSmallTypes,itemNameSub
											,projectamountbefore,totalpackageamountbefore,outdiscount,indiscount,inamountafter));
									var pop = arr.pop();
									var parent = arr.length==1? subId + 'Row-' + arr[0]:"sub" + subId + "Row-" + arr.join('.');								
									var siblings = (parent.indexOf('sub')==-1?'sub':'') + parent + '.';								
									var $parent = $html.find("tr[id='" + parent + "']");
									var $siblings = $html.find("tr[id^='" + siblings + "']");
									var siblingslen = $siblings.length;																					
									setReadonly($parent);
									
									if (siblingslen > 0) {
										var $last = $($siblings[siblingslen - 1]);
										var lastId = $last.prop('id');
										if (lastId.split('.').pop() <= pop - 1) {
											$last.after($trHtml);													 
										}
									} else if ($parent.length == 1 && pop == '1') {
										$parent.after($trHtml);
									}											
								}
								if (level == 3) {					
									var id = "sub"+subId+"Row-"+subRowId;												
									var types = subRowId.split('.');        
							        var feeTypes = types[0],feeSmallTypes = types[0]+'.'+types[1];								        												
									var $trHtml = $($('#layui-row-tr2').html().format(id,level,subRowId,subId,costType,feeTypes,feeSmallTypes,itemNameSub
											,projectamountbefore,totalpackageamountbefore,outdiscount,indiscount,inamountafter));
									var pop = arr.pop();
									var parent = arr.length==1? subId + 'Row-' + arr[0]:"sub" + subId + "Row-" + arr.join('.');								
									var siblings = (parent.indexOf('sub')==-1?'sub':'') + parent + '.';								
									var $parent = $html.find("tr[id='" + parent + "']");
									var $siblings = $html.find("tr[id^='" + siblings + "']");
									var siblingslen = $siblings.length;																					
									setReadonly($parent);
									
									if (siblingslen > 0) {
										var $last = $($siblings[siblingslen - 1]);
										var lastId = $last.prop('id');
										if (lastId.split('.').pop() <= pop - 1) {
											$last.after($trHtml);													 
										}
									} else if ($parent.length == 1 && pop == '1') {
										$parent.after($trHtml);
									}											
								}
							}						
							$contractList.append($html);
						});
					}
					form.render();
				}
			}
		});
	}

	//合同开工日期
	function checkValueVerifyBeginBuildDate(laydate, $) {
		var Data_id_contractCommencementDate = laydate
			.render({
				elem : '#id_contractCommencementDate',
				trigger : 'click',
				done : function(value, date) {
					var valueContractconstructionperioddays = $(
							"#id_Contractoperationperiodyear").attr("value");//合同工期（天）
					var rgx = /^([-]?)([0-9](\d+)?(\.\d{1,2})?$)|(^\d\.\d{1,2}$)/;
					if (rgx.test(valueContractconstructionperioddays)) {//'请输入正确数字，且保留两位小数！'
						var nextday1 = addDate(value,
								valueContractconstructionperioddays);
						$("#id_contractCompletionDate")
								.attr("value", nextday1);//合同竣工日期
					}
				}
			});
	}
	//实际开工日期
	function checkValueVerifyActBeginDate(laydate, $) {
		var Data_id_actualCommencementDate = laydate
			.render({
				elem : '#id_actualCommencementDate',
				trigger : 'click',
				done : function(value, date) {
					var valueContractconstructionperioddays = $(
							"#id_Contractoperationperiodyear").attr("value");//合同工期（天）
					var rgx = /^([-]?)([0-9](\d+)?(\.\d{1,2})?$)|(^\d\.\d{1,2}$)/;
					if (rgx.test(valueContractconstructionperioddays)) {//'请输入正确数字，且保留两位小数！'
						var nextday1 = addDate(value,
								valueContractconstructionperioddays);
						$("#id_adjustedCompletionDate")
								.attr("value", nextday1);//调整后竣工日期
					}
				}
			});
	}

	/**
	 * [dateAddDays 从某个日期增加n天后的日期]
	 * @param  {[string]} dateTemp  [日期字符串]
	 * @param  {[int]} days [增加的天数]
	 * @return {[string]}[增加n天后的日期字符串]
	 */
	 function addDate(dateTemp, days) {
	    var nDate = new Date(dateTemp);
	    var millSeconds = Math.abs(nDate) + (days * 24 * 60 * 60 * 1000);
	    var rDate = new Date(millSeconds);
	    var year = rDate.getFullYear();
	    var month = rDate.getMonth() + 1;
	    month = month < 10 ? "0"+month : month;
	    var date = rDate.getDate();
	    date = date < 10 ? "0"+date : date;
	    return (year + "-" + month + "-" + date);
	}
	// 请输入正确数字，且保留两位小数！
	function checkValueverifyNumber2(obj) {
		var $ = layui.$, form = layui.form
		if (obj.value == '' || obj.value == null) {
			return;
		}
		var rgx = /^([-]?)([0-9](\d+)?(\.\d{1,2})?$)|(^\d\.\d{1,2}$)/;

		var boolrgx = rgx.test(obj.value);// true 
		var periodDays = parseFloat(obj.value)*365;
		//判断合同建设期是否有小数点，有则需加一天
		if(parseFloat(periodDays) > parseFloat((periodDays+"").split(".")[0])){
			periodDays = parseFloat((periodDays+"").split(".")[0]) + 1;
		}
		if (boolrgx) {
			if (obj.id == "id_Contractconstructionperiodyear") {//合同工期(年)
				$("#id_Contractoperationperiodyear").attr("value",periodDays);//合同工期(天)
			}
		} else {
			obj.value=0;
			layer.msg('请输入正确数字，且保留两位小数！');
		}
	}
	//'请输入正确数字，且保留两位小数！'
	function isNumberAndFloat1(str) {
		var $ = layui.$, form = layui.form
		if (str.value == '' || str.value == null) {
			return;
		}
		var rgx = /^([-]?)([0-9](\d+)?(\.\d{1,2})?$)|(^\d\.\d{1,2}$)/;

		var boolrgx = rgx.test(str.value);// true 
		if (boolrgx) {
			return true;
		} else {
			str.value =0;
			return false;
		}
	}
	//'请输入正确数字，且保留两位小数！'
	function isNumberAndFloat2(str) {
		var rgx = /^([-]?)([0-9](\d+)?(\.\d{1,2})?$)|(^\d\.\d{1,2}$)/;

		var boolrgx = rgx.test(str);// true 
		if (boolrgx) {
			return true;
		} else {
			return false;
		}
	}
	
	function deleteSubRow(t) {
		var $ = layui.$;
		layui.layer.confirm('确定删除？',{
							icon : 3,
							title : '提示'
						},
						function(index) {
							var $tr = $(t).parents('tr');
							var id = $tr.prop("id");
							var level = $tr.attr("level");
							var arr = id.split('.');
							arr.pop();
							var prefix = arr.join('.') + '.';
							
							var $waitRemove = $('tr[id="`"], tr[id^="`."]'
									.replace(/`/g, id));
							if (level == '2') {
								var waitRemoveLast = $waitRemove[$waitRemove.length - 1];
								var waitRemoveLastId = $(waitRemoveLast).prop("id");
								var waitRemoveLastIndex = null;
								
								$("tr[id^='" + prefix + "']").each(function(index) {
											if (this.id == waitRemoveLastId) {
												waitRemoveLastIndex = index;
												return false;
											}
								});
								
								$("tr[id^='" + prefix + "']:gt(" + waitRemoveLastIndex + ")")
										.each(
												function(index) {
													if ($(this).attr('level') == '3') {
														var temp = this.id
																.split('-');
														var numList = temp[1]
																.split('.');
														numList[1] = parseInt(numList[1]) - 1;
														var subRowId = numList
																.join('.');
														var nextId = temp[0]
																+ '-'
																+ subRowId;
																												
														var types = subRowId.split('.');        
								                        var feeSmallTypes=types[0]+'.'+types[1];
								                		
								                        $(this).attr('id', nextId).find(".label").text(subRowId)
								                		.end().find("input[type=hidden]:first").val(subRowId)
								                		.end().find("input[type=hidden].feeSmallTypes").val(feeSmallTypes);	
								                		
								                		
													}
												});
							}
							$waitRemove.remove();

							var $subRows = $("tr[id^='" + prefix + "'][level="+ level + "]");
							var rowId = prefix.split('-')[1];
							$subRows.each(function(index) {
								var sortid = index + 1
								var subRowId = rowId + sortid;
								var nextId = prefix + sortid;
								
				                var types = subRowId.split('.');        
				                var feeSmallTypes = types[0]+'.'+types[1];                
				                $(this).attr('id', nextId).find(".label").text(subRowId)
				                .end().find("input[type=hidden]:first").val(subRowId)
				                .end().find("input[type=hidden].feeSmallTypes").val(feeSmallTypes);															

							});
							if($subRows.length==0){
								var $parentRow = null;
								if (arr.length == 1) {
									$parentRow = $('#' + arr[0].replace('sub', ''));
								}
								if (arr.length == 2) {
									$parentRow = $('[id="' + arr.join('.')+'"]');
								}
								removeReadonly($parentRow)
							}
							parentGroup($, 'outdiscount', id, $('.contract-list'));
							parentGroup($, 'indiscount', id, $('.contract-list'));
							
							layui.layer.close(index);
						});
	}
	
	function removeReadonly($t) {
		if ($t) {
			$t.find('input[type=text].totalpackageamountbefore').removeProp('readonly').attr('lay-verify','required|floatNumber');
			$t.find('input[type=text].indiscount').removeProp('readonly').attr('lay-verify','required|floatNumber');
			if($t.find('button').hasClass("add-sub-row") && $t.find('button').hasClass("del-sub-row")){
				$t.find('input[type=text].projectamountbefore').removeProp('readonly').attr('lay-verify','required|floatNumber');
				$t.find('input[type=text].outdiscount').removeProp('readonly').attr('lay-verify','required|floatNumber');
			}
		}
	}

	function setReadonly($t) {
		if ($t) {
			$t.find('input[type=text].projectamountbefore').prop('readonly', true).removeAttr('lay-verify');
			$t.find('input[type=text].outdiscount').prop('readonly', true).removeAttr('lay-verify');
			$t.find('input[type=text].totalpackageamountbefore').prop('readonly', true).removeAttr('lay-verify');
			$t.find('input[type=text].indiscount').prop('readonly', true).removeAttr('lay-verify');
		}
	}
	
	//新增二级行
	function addNewRow(t) {
		var $ = layui.$;
		var $parentRow = $(t).parents('tr');
		var level = parseInt($parentRow.attr('level')) + 1;
		var parentId = $parentRow.attr('id');
		var subParentId =  'sub'+ parentId + '.';
		var $subRows = $("tr[id^='" + subParentId + "']");
		var $lastRow = ($subRows.length > 0) ? $("tr[id^='" + subParentId + "']:last") : $parentRow;
		var arr = $lastRow.attr('id').split('.');

		var count = $subRows.length > 0 ? arr[parentId.split('.').length] - 0 : 0;
		var subId = subParentId.replace(/^sub(.*)Row.*$/, '$1');
		count++;
		var nextId = subParentId + count;
		var subRowId = nextId.split('-')[1];
		var types = subRowId.split('.');        
        var feeTypes = types[0],feeSmallTypes = types[0]+'.'+types[1];
        var itemNameSub = $lastRow.find('.itemNameSub').val();
        
        
		var $rowHtml = $($('#layui-row-tr').html().format(nextId,level,subRowId,subId,'',feeTypes,feeSmallTypes,itemNameSub,'','','','',''));
		$rowHtml.find("td:last").html('<button type="button" class="layui-btn layui-btn-sm add-sub-row" ><i class="layui-icon">&#xe654;</i></button><button type="button" class="layui-btn layui-btn-sm del-sub-row"   ><i class="layui-icon">&#xe640;</i></button>');
		$lastRow.after($rowHtml);
		layui.form.render();
	}
	
	//新增三级行
	function addSubRow(t) {
		var $ = layui.$;
		var $parentRow = $(t).parents('tr');
		var level = parseInt($parentRow.attr('level')) + 1;
		var parentId = $parentRow.attr('id');
		var subParentId = parentId + '.';
		var $subRows = $("tr[id^='" + subParentId + "']");
		var $lastRow = ($subRows.length > 0) ? $("tr[id^='" + subParentId + "']:last") : $parentRow;
		var arr = $lastRow.attr('id').split('.');

		var count = $subRows.length > 0 ? arr[parentId.split('.').length] - 0 : 0;
		var subId = subParentId.replace(/^sub(.*)Row.*$/, '$1');
		count++;
		var nextId = subParentId + count;
		var subRowId = nextId.split('-')[1];
		var types = subRowId.split('.');        
        var feeTypes = types[0],feeSmallTypes = types[0]+'.'+types[1];
        var itemNameSub = $lastRow.find('.itemNameSub').val();
        
        
		var $rowHtml = $($('#layui-row-tr2').html().format(nextId,level,subRowId,subId,'',feeTypes,feeSmallTypes,itemNameSub,'','','','',''));
		$rowHtml.find("td:last").html('<button type="button" class="layui-btn layui-btn-sm del-sub-row"   ><i class="layui-icon">&#xe640;</i></button>');
		if($subRows.length == 0){
			setReadonly($parentRow);
		}
		$lastRow.after($rowHtml);
		layui.form.render();
	}
</script>